import { useEffect, useRef } from 'react';

/**
 *
 * 更多说明：https://overreacted.io/zh-hans/making-setinterval-declarative-with-react-hooks/
 * @param {function} callback
 * @param {number | null} delay 间隔时间，设置null 表示暂停
 */
const useInterval = (callback, delay) => {
  const savedCallback = useRef(() => {});

  useEffect(() => {
    savedCallback.current = callback;
  });

  useEffect(() => {
    if (delay !== null) {
      const interval = setInterval(() => savedCallback.current(), delay || 0);
      return () => clearInterval(interval);
    }

    return undefined;
  }, [delay]);
};

export default useInterval;
